package com.ddtech.config;

import cn.hutool.json.JSONUtil;
import com.ddtech.framework.monitor.consolelog.ConsoleLog;
import com.ddtech.framework.monitor.consolelog.ConsoleLogQueue;
import com.ddtech.framework.monitor.vo.Server;
import com.ddtech.utils.ThreadExecutors;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 配置WebSocket消息代理端点，即stomp服务端
 *
 * @link https://cloud.tencent.com/developer/article/1096792
 */
@Slf4j
@EnableWebSocketMessageBroker
@Configuration
public class WebSocketAutoConfiguration implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;


    private Logger logger = LoggerFactory.getLogger(WebSocketAutoConfiguration.class);

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket")
                .addInterceptors(new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
                        //检查是否有权限

                        return true;
                    }

                    @Override
                    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

                    }
                })
                .setAllowedOrigins("*")
                .withSockJS();
    }

    /**
     * 推送服务器信息/topic/server
     */
    @PostConstruct
    public void pushServer() {
        ScheduledExecutorService executorService = ThreadExecutors.getExecutorService();
        Runnable runnable = () -> {
            try {
                Server server = new Server();
                server.copyTo();
                messagingTemplate.convertAndSend("/topic/server",server);
            } catch (Exception e) {
                log.warn("推送服务器信息失败:{}", e.getMessage());
            }
        };
        executorService.scheduleAtFixedRate(runnable, 1, 2, TimeUnit.SECONDS);
    }

    /**
     * 推送日志到/topic/consolelog
     */
    @PostConstruct
    public void pushLogger() {
        ScheduledExecutorService executorService = ThreadExecutors.getExecutorService();
        Runnable runnable = () -> {
            for (; ; ) {
                try {
                    ConsoleLog log = ConsoleLogQueue.getInstance().poll();
                    if (log != null && messagingTemplate != null) {
                        messagingTemplate.convertAndSend("/topic/consolelog", log);
                    }
                } catch (Exception e) {
                    log.warn("推送日志失败:{}", e.getMessage());
                }
            }
        };
        executorService.submit(runnable);
    }
}